//公共函数库

var layer = require('layer');
var alert = require('{layer}/alert');
var util = require('util');
var template = require('template');
var layer = require('layer');
var json = require('{polyfill}/json');
return {
     /**
     * 计算
     */
    jisuan: function () {
        var th = this;
        var type = arguments[0];
        var arg = arguments;
        var result = 0;
        switch (type) {
            case '+':
                result = th.xiangjia(arg);
                break;
            case '-':
                result = th.xiangjian(arg);
                break;
            case '*':
                result = th.chengfa(arg);
                break;
            case '/':
                result = th.chufa(arg);
                break;
        }
        return result
    },
    quzheng: function (param) {
        var args = param + '';
        var index = args.indexOf('.');
        var doubleLen = 0;
        if (index > 0) {
            doubleLen = args
                .substring(index + 1)
                .length
            param = param * 1 * Math.pow(10, doubleLen);
        }
        var p = [0, 0];
        var i = (param + '').indexOf('.');
        param = Math.round(param); //取最接近整数
        p.splice(0, 1, param);
        p.splice(1, 1, doubleLen);
        return p
    },
    //加法，减法，除法，计算比较麻烦，需要取到小数位数最大的值
    xiangjia: function (args) {
        var th = this;
        var con = 0,
            len = [],
            i,
            argLen = args.length,
            arg;
        for (i = 0; i < argLen; i++) {
            if (i > 0) {
                len[i - 1] = th.quzheng(args[i])[1];
            }
        }
        var maxLen = Math
            .max
            .apply(null, len);
        for (i = 0; i < argLen; i++) {
            if (i > 0) {
                con += th.quzheng(args[i])[0] * 1 * Math.pow(10, (maxLen - len[i - 1]));
            }
        }
        return con / Math.pow(10, maxLen)
    },
    // 减法
    xiangjian: function (args) {
        var th = this,
            con = 0,
            len = [],
            i,
            argLen = args.length,
            arg;
        for (i = 0; i < argLen; i++) {
            if (i > 0) {
                len[i - 1] = th.quzheng(args[i])[1];
            }
        }
        var maxLen = Math
            .max
            .apply(null, len);
        con = th.quzheng(args[1])[0] * 1 * Math.pow(10, (maxLen - len[0]));
        for (i = 0; i < argLen; i++) {
            if (i > 1) {
                con = con * 1 - (th.quzheng(args[i])[0] * 1 * Math.pow(10, (maxLen - len[i - 1]))) * 1;
            }
        }
        return con / Math.pow(10, maxLen)
    },
    //乘法需要求到所有取正的倍数
    chengfa: function (args) {
        var th = this,
            con = 1,
            len = 0,
            i,
            argLen = args.length,
            arg;
        for (i = 0; i < argLen; i++) {
            if (i > 0) {
                arg = th.quzheng(args[i])
                con = arg[0] * 1 * con;
                len += arg[1];
            }
        }
        return con / Math.pow(10, len)
    },
    //除法需要求最长小数位数
    chufa: function (args) {
        var th = this,
            con = 1,
            len = [],
            i,
            argLen = args.length,
            arg;
        for (i = 0; i < argLen; i++) {
            if (i > 0) {
                len[i - 1] = th.quzheng(args[i])[1];
            }
        }
        var maxLen = Math
            .max
            .apply(null, len);
        con = th.quzheng(args[1])[0] * 1 * Math.pow(10, (maxLen - len[0]));
        for (i = 0; i < argLen; i++) {
            if (i > 1) {
                con = con * 1 / (th.quzheng(args[i])[0] * 1 * Math.pow(10, (maxLen - len[i - 1]))) * 1;
            }
        }
        return con
    },
    setCookie:function (name,value,timers) {//设置cookie
        var strsec = (timers && this.getsec(timers)) || '';
        var exp = new Date();
        exp.setDate(exp.getDate() + strsec*1);
        console.log(this.isArrayObject(value))
        if(this.isArrayObject(value)) {
            value = json.stringify(value)
        }
        // document.cookie = "adminUser" + "="+ "%7B%22cPhone%22%3A%2215888953601%22%2C%22cRealname%22%3A%22%u7CFB%u7EDF%u7BA1%u7406%u5458%22%2C%22cUsername%22%3A%22zjpt%22%2C%22cUsertype%22%3A%22SUPER%22%7D" + ";path=/" 
        document.cookie = name + "="+ escape (value) + ";path=/" + ((!timers) ? "" : ";expires="+exdate.toGMTString())
    },
    getCookie:function(name) {//获取cookie
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"),regs = /^(\[|\{)[\s\S]*(\]|\})$/g;
        if(arr=document.cookie.match(reg)){
            if (regs.test(unescape(arr[2]))) {
                return JSON.parse(unescape(arr[2]))
            }
            return unescape(arr[2]);
        }
        else
            return null;
    },
    isArrayObject: function(obj){
        if(!Nui.type(obj, 'Object') && obj.constructor !== Object && !Nui.isArray(obj)){
            return false;
        }
        return true
    },
    delCookie:function(name){//删除cookie
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        if (!name) { 
            var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
            console.log(keys)
            if(keys) {
                for (var i = keys.length; i--;){ 
                    document.cookie= keys[i] + '=;  path=/;expires=' + 'Thu, 01 Jan 1970 00:00:00 GMT'
                }
            }
            return
        } 
        var cval=this.getCookie(name);
        if(cval!=null){
            document.cookie= name + "=" + cval+";expires="+exp.toGMTString();
        }
    },
    getsec:function(str){//处理cookie保存时间,默认毫秒
        var timers=str.replace(/s|d|h/g,'')
        var timersType=str.replace(/\d/g,'')
        if (timersType=="s") {
            return timers*1000;
        }
        else if (timersType=="h") {
            return timers*60*60*1000;
        }
        else if (timersType=="d") {
            return timers*24*60*60*1000;
        }
        else {
            return timers;
        }
    },
    getData:function(e, elem){
        if(elem.hasClass('table-row')){
            return elem.data();
        }
        return elem.closest('.table-row').data();
    },
    checkedData:function(e, elem){
        var data = this.datagrid.checkedData();
        if(!data.length){
            alert('<p class="f-tac">请勾选需要操作的行</p>')
            return false
        }
        return data
    },
    location:function(url){
        location.href = basePath + url.replace(/^\/+/, '')
    },
    enabled:function(e, elem){
        return !elem.hasClass('ui-button-disabled') && !elem.hasClass('ui-input-disabled') && !elem.hasClass('s-dis')
    },
    print:function(url, params){
        if(util.isInstallPDF()){
            layer({
                height:160,
                content:renders({
                    <div class="f-tac e-pt20">
                        <i class="iconfont f-corange f-fs20 f-vam">&#xe608;</i>
                        <span class="f-dib e-mt-1 e-ml5 f-vam">打印需要借助PDF阅读器，请先下载！</span>
                    </div>
                }),
                button:[{
                    id:'cancel'
                },{
                    id:'download',
                    name:'normal',
                    text:'下载',
                    callback:function(){
                        util.location('http://rj.baidu.com/soft/detail/12612.html?ald', '_blank')
                    }
                }]
            })
            return false
        }
        this.request(url, params)
    },
    /**
     * @func 打开新窗口表单提交
     * @param url <String> 接口
     * @param params <Object> 参数
     */
    request:function(url, params){
        if(!url){
            return
        }
        var tpl = renders({
            <form class="f-dn" method="post" target="_blank" action="<%url%>">
                <%each params%>
                    <input type="hidden" name="<%index%>" value="<%$value%>">
                <%/each%>
            </form>
        })
        var form = $(template.render(tpl, {url:Nui.domain+url, params:params})).appendTo('body');
        form.submit();
        form.remove();
    },
    /**
     * @func 验证用户权限对按钮进行隐藏
     * @param authoritys <String> 权限列表
     */
    verify:function(authoritys){
        if(authoritys){
            $('[authority]:not(.ui-button-disabled)').each(function(){
                var elem = $(this);
                var authority = elem.attr('authority');
                if(authoritys.indexOf(authority) === -1){
                    elem.addClass('ui-button-disabled s-dis')
                }
            });
        }
    }
}